import styles from './index.less';
import { Filter } from './components/Filter';
import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { useSetState } from 'ahooks';
import { Container } from './components/Container';
import { getSelect, priceForecastlist, queryMarketList } from './services';
import { HttpCode } from '#/utils/contacts';
import { connect } from 'umi';
import { PageLoading, TRDefault } from '@/components';
import moment from 'moment';
import { leftOptions, rightOptions } from './constant';
import {
  getChartFilterOptions,
  getChartHeadFilterOptions,
  getData,
  getDefaultAggregateValue,
  getHead,
} from './helper';
import { message, Modal, Spin } from 'antd';
import { ExclamationCircleOutlined } from '#/utils/antdIcons';
import { getTreeByCodes } from '@/utils';

const DayPriceForecastAccuracy = ({ menuCode, buttonPermissions }) => {
  // const [stations, setStations] = useState([]);

  const [containerLoading, setContainerLoading] = useState(false);

  // 省份
  const [province, setProvince] = useState([]);

  const [error, setError] = useState('');

  const [spinning, setSpinning] = useState(true);

  const [tableData, setTableData] = useSetState({
    columns: [],
  });

  const [filterParams, setFilterParams] = useSetState({
    date: [moment(), moment()],
    stationIds: [],
  });

  // 聚合的选择
  const [aggregateSelect, setAggregateSelect] = useState({
    leftSelect: leftOptions.slice(0, 4),
    rightSelect: rightOptions,
  });

  const [chartFilter, setChartFilter] = useState([]);

  const [chartHeadFilter, setChartHeadFilter] = useState([]);

  // 筛选的options集合
  const [optionObj, setOptionObj] = useState({});

  // 偏差量数据
  const [deviationQuantityData, setDeviationQuantityData] = useState({});

  useEffect(() => {
    (async () => {
      await init();
    })();
  }, []);

  const init = async () => {
    // 获取数据权限
    const [res, selectRes] = await Promise.all([queryMarketList(menuCode), getSelect()]);
    let stationIds = [];
    if (res?.statusCode === HttpCode.SUCCESS) {
      const power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
      stationIds = initDataPower(power);
    } else {
      setError(res?.message || '系统异常');
    }
    if (selectRes?.statusCode === HttpCode.SUCCESS) {
      const data = _.cloneDeep(selectRes.data || {});
      data.datasource = data?.datasource?.map((i) => ({ label: i, value: i }));
      data.evaluationIndicator = data?.evaluationIndicator?.map((i) => ({ label: i, value: i }));
      data.leadTime = data?.leadTime?.map((i) => ({ label: i, value: i }));
      const params = {
        date: [moment(), moment()],
        datasource: selectRes.data?.datasource || [],
        evaluationIndicator: selectRes.data?.evaluationIndicator || [],
        version: selectRes.data?.leadTime || [],
        stationIds: stationIds,
      };
      setFilterParams(params);
      setOptionObj(data);
      await callFilterServer(aggregateSelect.leftSelect, aggregateSelect.rightSelect, params);
    } else {
      message.error(res.message || '获取筛选配置项失败!');
    }
    setSpinning(false);
  };

  const initDataPower = (data) => {
    // const provinceArr = [];
    // const stationIds = []
    // const fun = (item, value) => {
    //   if (value.children instanceof Array) {
    //     value.children.map((i) => {
    //       fun(item, i);
    //     });
    //   } else {
    //     stationIds.push(value.value);
    //     item.children.push(value);
    //   }
    // };
    // const stationArr = data?.map((item) => {
    //   const v = _.cloneDeep(item);
    //   v.children = [];
    //   provinceArr.push(v);
    //   fun(v, item);
    //   return v;
    // });
    // setStations(stationArr);
    setProvince(data);
    return _.flattenDeep(
      data?.map((a) => a?.children?.map((x) => x?.children?.map((y) => y.value))),
    );
  };

  // const getDeparture = async (headFilter, filter) => {
  //   const deviationParams = getDeviationParams(headFilter, filter, stations);
  //   const res = await getDeviationAmount(deviationParams);
  //   if (res?.statusCode === HttpCode.SUCCESS) {
  //     setDeviationQuantityData(res.data);
  //   } else {
  //     message.error(res.message || '获取偏差量失败！');
  //   }
  // };
  // 调用筛选接口
  const callFilterServer = async (leftAggregate, rightAggregate, params) => {
    setContainerLoading(true);
    const paramsData = params || filterParams;
    paramsData.startDate = paramsData?.date?.[0]?.format('YYYY-MM') || '';
    paramsData.endDate = paramsData?.date?.[1]?.format('YYYY-MM') || '';
    const [order, headOrder] = getDefaultAggregateValue(leftAggregate, rightAggregate);
    const res = await priceForecastlist({
      flexAggrBody: { order, headOrder },
      param: paramsData,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setAggregateSelect({
        leftSelect: leftAggregate,
        rightSelect: rightAggregate,
      });
      const columns = res.data ? getHead(res.data.head, order) : [];
      const dataSource = res.data ? getData(res.data.data) : [];
      const chartFilterOptions = getChartFilterOptions(leftAggregate, dataSource);
      const chartHeadFilterOptions = res.data
        ? getChartHeadFilterOptions(rightAggregate, res?.data?.select)
        : [];
      setChartHeadFilter(chartHeadFilterOptions);
      setChartFilter(chartFilterOptions);
      setTableData({
        columns,
        dataSource,
      });
      // if (res.data) {
      //   await getDeparture(chartHeadFilterOptions, chartFilterOptions);
      // }
    } else {
      message.error(res.message || '获取数据失败!');
    }
    setContainerLoading(false);
  };

  // 筛选
  const handleFiltrate = async (type, leftSelect, rightSelect) => {
    // 如果type为0则是筛选，type为1则是聚合
    let leftAggregate = type ? leftSelect : leftOptions.slice(0, 4);
    const rightAggregate = type ? rightSelect : rightOptions;
    // 判断场站的位置是否在省份之前，如果在省份之前则提示，确定后省份与场站位置交换
    const stationIndex = leftAggregate.findIndex((i) => i.value === 'stationId');
    const provinceIndex = leftAggregate.findIndex((i) => i.value === 'provinceId');
    if (stationIndex !== -1 && provinceIndex !== -1) {
      if (stationIndex < provinceIndex) {
        Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined />,
          content: '灵活聚合时，场站不能在省份之前！',
          async onOk() {
            [leftAggregate[stationIndex], leftAggregate[provinceIndex]] = [
              leftAggregate[provinceIndex],
              leftAggregate[stationIndex],
            ];
            await callFilterServer(leftAggregate, rightAggregate);
          },
        });
      } else {
        await callFilterServer(leftAggregate, rightAggregate);
      }
    } else {
      await callFilterServer(leftAggregate, rightAggregate);
    }
  };

  if (spinning) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!province?.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.container}>
      <div className={styles.toolbar}>
        <Filter
          buttonPermissions={buttonPermissions}
          province={province}
          containerLoading={containerLoading}
          optionObj={optionObj}
          filtrateClick={() => handleFiltrate(0)}
          filterParams={filterParams}
          setFilterParams={setFilterParams}
          // stations={stations}
        />
      </div>
      <div className={styles.contentAll}>
        <div className={styles.content}>
          {containerLoading ? (
            <Spin className={styles.spinning} tip={'数据加载中'} spinning={true} />
          ) : (
            <Container
              // getDeparture={getDeparture}
              setChartFilter={setChartFilter}
              deviationQuantityData={deviationQuantityData}
              aggregateSelect={aggregateSelect}
              chartHeadFilter={chartHeadFilter}
              setChartHeadFilter={setChartHeadFilter}
              columns={tableData.columns}
              dataSource={tableData.dataSource}
              chartFilter={chartFilter}
              handleFiltrate={handleFiltrate}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(DayPriceForecastAccuracy);
